﻿CREATE FUNCTION [dbo].[yaf_forum_topics]
               (@ForumID INT)
RETURNS INT
AS
  BEGIN
	DECLARE  @NumTopics INT
		DECLARE  @tmp INT
		SELECT @NumTopics = NumTopics
		FROM   dbo.yaf_Forum
		WHERE  ForumID = @ForumID
		IF EXISTS (SELECT 1
					FROM   dbo.yaf_Forum
					WHERE  ParentID = @ForumID)
		BEGIN
			DECLARE c CURSOR  FOR
				SELECT ForumID
				FROM   dbo.yaf_Forum
				WHERE  ParentID = @ForumID
				OPEN c
				FETCH NEXT FROM c
				INTO @tmp
				WHILE @@FETCH_STATUS = 0
				BEGIN
					SET @NumTopics = @NumTopics + dbo.yaf_forum_topics(@tmp)
						FETCH NEXT FROM c
						INTO @tmp
					END
				CLOSE c
				DEALLOCATE c
			END
		RETURN @NumTopics
	END


